package 力扣._56_合并区间;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Solution {
    public int[][] merge(int[][] intervals) {
        List<int[]> result = new ArrayList<>();
        List<int[]> list = new ArrayList<>();
        for (int[] interval : intervals) {
            list.add(new int[]{interval[0], interval[1]});
        }
        list.sort(Comparator.comparingInt(o -> o[0]));    //按照左端点大小排序
        for (int[] ints : list) {
            if (result.size() == 0)
                result.add(ints);
            else {
                //无交集
                if (result.get(result.size() - 1)[1] < ints[0])
                    result.add(ints);
                else {  //有交集
                    result.get(result.size() - 1)[1] = Math.max(result.get(result.size() - 1)[1], ints[1]);
                }
            }
        }
        return result.toArray(new int[result.size()][]);
    }
}
